<template>
  <view class="login-container" :style="{ paddingTop: navHeight + 'px' }">
    <!-- 标题区域 -->
    <view class="title-section">
      <text class="page-title">选择您的私人秘书</text>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <!-- 角色选择网格 -->
    <view v-else class="character-grid">
      <view v-for="(character, index) in characters" :key="index" class="character-card"
        :class="{ 'selected': selectedCharacter === character.app_secret }" @tap="selectCharacter(character)">
        <view class="character-avatar-container">
          <!-- 图片加载状态 -->
          <view v-if="imageLoadingStates[index]" class="avatar-loading">
            <view class="avatar-loading-spinner"></view>
          </view>
          <view class="character-avatar" :style="{ backgroundImage: `url(${character.avatar})` }"></view>
        </view>
        <!-- <image class="character-avatar" :src="character.avatar" mode="aspectFill"></image> -->
        <view class="character-label">
          <text class="character-name">{{ character.name }}</text>
        </view>
        <!-- 选中状态指示器 -->
        <view v-if="selectedCharacter === character.app_secret" class="selection-indicator">
          <text class="checkmark">✓</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮区域 -->
    <view class="button-section">
      <!-- <button class="skip-btn" @tap="skipSelection">跳过</button> -->
      <button class="confirm-btn" @tap="confirmSelection">确定</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      navHeight: '', //整体顶部导航栏的高度
      statusBarHeight: '', //状态栏高度
      selectedCharacter: null, // 选中角色
      characters: [], // 初始化为空数组，通过API获取数据
      loading: true, // 添加加载状态
      imageLoadingStates: [] // 图片加载状态数组
    }
  },
  onLoad() {
    let {
      statusBarHeight,
      system
    } = uni.getSystemInfoSync();
    this.statusBarHeight = statusBarHeight;
    this.navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48);
    this.getOfficialCharacters();
    // this.getUserInfo();
  },
  onShow() {
    this.getOfficialCharacters();
    // 1、获取用户信息 2、判断bot_appsecret是否为空，空就要选择私人秘书，有值就跳首页
    this.getUserInfo();
  },
  methods: {
    // 获取用户信息
    getUserInfo() {
      let userInfo = uni.getStorageSync('userInfo');
      const userid = userInfo?.data?.userid || userInfo?.userid || '';
      this.$Request.postApi('/bot/api/agentgetuserinfo', { userid: userid }).then(res => {
        if (res.status === 1) {
          this.userDetail = res.data;
          // 更新本地缓存
          uni.setStorageSync('userInfo', res.data);
          // bot_appsecret有值跳转到首页
          if (res.data.bot_appsecret) {
            uni.navigateTo({
              url: `/pages/index?appSecret=${encodeURIComponent(res.data.bot_appsecret)}&userid=${encodeURIComponent(userid)}&formPage=home`
            })
          }
        } else {
          uni.showToast({ title: res.message || '获取用户信息失败', icon: 'none' });
        }
      }).catch(() => {
        uni.showToast({ title: '网络错误', icon: 'none' });
      });
    },
    // 获取官方私人助理列表
    getOfficialCharacters() {
      this.loading = true;
      this.$Request.getApi("/bot/api/getagentcofficiallist").then((res) => {
        this.loading = false;
        if (res.status == 1 && res.data && res.data.length > 0) {
          // 处理API返回的数据
          this.characters = res.data.map(item => {
            return {
              name: item.title,
              avatar: item.headimgurl,
              app_secret: item.app_secret,
              id: item.id
            }
          });
          // 初始化图片加载状态数组
          this.imageLoadingStates = new Array(this.characters.length).fill(true);
          // 检测每个图片的加载状态
          this.checkImageLoading();
        } else {
          // 处理数据为空的情况
          uni.showToast({
            title: '获取数据失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        this.loading = false;
        console.error('获取助理列表失败:', err);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      });
    },
    // 检测图片加载状态
    checkImageLoading() {
      // 使用uni-app兼容的方式检测图片加载
      this.characters.forEach((character, index) => {
        // 先设置一个延迟，模拟图片加载过程
        setTimeout(() => {
          // 检查图片是否有效
          if (character.avatar && character.avatar.trim() !== '') {
            // 使用uni.getImageInfo来检测图片是否可加载
            uni.getImageInfo({
              src: character.avatar,
              success: (res) => {
                // 图片加载成功
                this.$set(this.imageLoadingStates, index, false);
              },
              fail: (err) => {
                // 图片加载失败，也隐藏加载状态
                this.$set(this.imageLoadingStates, index, false);
                console.error(`图片加载失败: ${character.avatar}`);
              }
            });
          } else {
            // 如果没有头像URL，直接隐藏加载状态
            this.$set(this.imageLoadingStates, index, false);
          }
        }, 500 + index * 100); // 添加延迟，避免同时加载
        
        // 备用方案：设置最大加载时间，确保加载状态不会一直显示
        setTimeout(() => {
          if (this.imageLoadingStates[index]) {
            this.$set(this.imageLoadingStates, index, false);
          }
        }, 3000 + index * 200); // 3秒后强制隐藏加载状态
      });
    },
    // 选择角色
    selectCharacter(character) {
      this.selectedCharacter = character.app_secret;
    },
    // 确认选择
    confirmSelection() {
      if (this.characters.length === 0 || this.selectedCharacter === null) {
        uni.showToast({
          title: '请选择私人秘书',
          icon: 'none'
        });
        return;
      }
      // 准备请求参数
      let params = {
        userid: uni.getStorageSync('userInfo').userid,
        appsecret: this.selectedCharacter
      }
      this.$Request.postApi("/bot/api/agentcsaveuseragent", params).then((res) => {
        uni.hideLoading();
        if (res.status === 1) {
          let userInfo = uni.getStorageSync('userInfo');
          const userid = userInfo?.data?.userid || userInfo?.userid || '';
          // 将选择的私人秘书app_secret同步更新到缓存中
          if (userInfo.data) {
            userInfo.data.bot_appsecret = this.selectedCharacter;
          } else {
            // 如果缓存结构是 userInfo
            userInfo.bot_appsecret = this.selectedCharacter;
          }
          uni.setStorageSync('userInfo', userInfo);
        
          uni.navigateTo({
            url: `/pages/index?appSecret=${encodeURIComponent(this.selectedCharacter)}&userid=${encodeURIComponent(userid)}&formPage=home`
          });
        } else {
          // API调用失败
          uni.showToast({
            title: res.message || '绑定失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        uni.hideLoading();
        console.error('绑定私人助理失败:', err);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      });
    }
  }
}
</script>

<style>
page {
  background-color: #ffffff;
}
</style>

<style lang="scss" scoped>
.login-container {
  min-height: 100vh;
  height: auto;
  background-image: url('/static/login/login3.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40rpx;
}

.title-section {
  // margin-top: 50rpx;
  margin-bottom: 50rpx;
  text-align: center;
}

.page-title {
  color: #ffffff;
  font-size: 36rpx;
  font-weight: 600;
  line-height: 1.4;
}

.character-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  width: 100%;
  // max-width: 600rpx;
  margin-bottom: 40rpx;
}

.character-card {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 20rpx;
  // padding: 20rpx;
  backdrop-filter: blur(15px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  transition: all 0.3s ease;
  width: 155px;
  height: 195px;
  box-sizing: border-box;
}

.character-card.selected {
  border-color: #2263EC;
  background: rgba(55, 88, 228, 0.15);
  transform: scale(1.02);
  border-width: 3rpx;
}

.character-avatar-container {
  position: relative;
  width: 100%;
  height: 680rpx;
  border-radius: 16rpx 16rpx 0 0;
  // margin-bottom: 20rpx;
  // object-fit: cover;
  // overflow: hidden;
  // flex: 1;
  background-size: cover;
  background-position: top;
  border-top-left-radius: 15rpx;
  border-top-right-radius: 15rpx;
  display: block;
  background-repeat: no-repeat;
}

.character-avatar {
  width: 100%;
  height: 305rpx;
  // height: 100%;
  border-radius: 16rpx 16rpx 0 0;
  background-size: cover;
  background-position: top;
  border-top-left-radius: 15rpx;
  border-top-right-radius: 15rpx;
  display: block;
  background-repeat: no-repeat;
  overflow: hidden;
}

.character-label {
  width: 100%;
  height: 76px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 0 0 16rpx 16rpx;
  text-align: center;
}

.character-name {
  color: #333333;
  font-size: 28rpx;
  font-weight: 600;
  letter-spacing: 1rpx;
}

.selection-indicator {
  position: absolute;
  bottom: -1px;
  right: 0;
  width: 27px;
  height: 23px;
  // background: #3758e4;
  background: #2263EC;
  border-radius: 18px 0 8px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  border: none;
}

.checkmark {
  color: #ffffff;
  font-size: 24rpx;
  font-weight: bold;
  margin-left: -4rpx;
  margin-bottom: -4rpx;
}

.button-section {
  display: flex;
  gap: 30rpx;
  width: 100%;
  max-width: 600rpx;
  margin-top: auto;
  margin-bottom: 60rpx;
}

.skip-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 80rpx;
  background-color: #ffffff;
  color: #000000;
  border: none;
  border-radius: 20rpx;
  font-size: 28rpx;
  font-weight: 500;
  transition: all 0.3s ease;
}

.confirm-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  height: 80rpx;
  background-color: #3b82f6;
  color: #ffffff;
  border: none;
  border-radius: 20rpx;
  font-size: 28rpx;
  font-weight: 500;
  transition: all 0.3s ease;
}

.skip-btn:active,
.confirm-btn:active {
  opacity: 0.8;
  transform: scale(0.98);
}

.character-card:active {
  transform: scale(0.98);
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 40rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid rgba(255, 255, 255, 0.3);
  border-top-color: #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-text {
  color: #ffffff;
  font-size: 28rpx;
}

.avatar-loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 16rpx 16rpx 0 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

.avatar-loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 6rpx solid rgba(255, 255, 255, 0.3);
  border-top-color: #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
</style>